package pl.radiomaryja.softcognito;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.client.ClientProtocolException;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
import org.xml.sax.SAXException;

import pl.radiomaryja.softcognito.R;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class RMFirstLevel extends ListActivity {

	public static String[] names;
	public static String[] links;

	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		new DownloadGroups().execute("");
	}

	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		final Bundle bundle = new Bundle();
		bundle.putString("link", links[position]);
		Log.i("Buttons", "List item button pressed");
		Intent myIntents = new Intent(this, RMSecondLevel.class);
		myIntents.putExtras(bundle);
		startActivityForResult(myIntents, 0);

		// Get the item that was clicked
		Object o = this.getListAdapter().getItem(position);
		String ss = Integer.toString(position);
		String keyword = o.toString();
		Toast
				.makeText(this, "You selected: " + keyword + ss,
						Toast.LENGTH_LONG).show();

	}

	private class DownloadGroups extends AsyncTask<String, Void, String> {

		ProgressDialog dialog;

		@Override
		protected String doInBackground(String... params) {
			try {
				getHtml();
			} catch (ClientProtocolException e) {
				Log.i("RMGET", "ClientProtocolException");
			} catch (IOException e) {
				Log.i("RMGET", "IOException");
			} catch (XPatherException e) {
				Log.i("RMGET", "XPatherException");;
			} catch (ParserConfigurationException e) {
				Log.i("RMGET", "ParserConfigurationException");
			} catch (SAXException e) {
				Log.i("RMGET", "SAXException");
			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			dialog.dismiss();
			RMFirstLevel.this.setListAdapter(new ArrayAdapter<String>(
					RMFirstLevel.this, R.layout.grouprowlayout, R.id.label,
					names));
		}

		@Override
		protected void onPreExecute() {
			dialog = ProgressDialog.show(RMFirstLevel.this, "",
					"Czekaj na dostęp do danych...", true);
		}

		@Override
		protected void onProgressUpdate(Void... values) {

		}

		public void getHtml() throws ClientProtocolException, IOException,
				XPatherException, ParserConfigurationException, SAXException,
				IOException, XPatherException {

			String AUDITIONS_XPATH = "//dt[@class='stitle']";
			String LINKS_XPATH = "//tr//td[@align='right']/a/@href";

			TagNode node;

			ArrayList<String> titlesList = new ArrayList<String>();
			ArrayList<String> linksList = new ArrayList<String>();

			URL url = new URL("http://www.radiomaryja.pl");
			URLConnection conn = url.openConnection();

			HtmlCleaner cleaner = new HtmlCleaner();
			CleanerProperties props = cleaner.getProperties();
			props.setAllowHtmlInsideAttributes(true);
			props.setAllowMultiWordAttributes(true);
			props.setRecognizeUnicodeChars(true);
			props.setTranslateSpecialEntities(true);
			props.setOmitComments(true);

			node = cleaner.clean(new InputStreamReader(conn.getInputStream(),
					Charset.forName("ISO-8859-2")));
			Object[] info_nodes = node.evaluateXPath(AUDITIONS_XPATH);
			Object[] links_nodes = node.evaluateXPath(LINKS_XPATH);

			if (info_nodes.length > 0) {
				for (Object linkNode : info_nodes) {
					String s = cleaner.getInnerHtml(((TagNode) linkNode));
					String tmpString = s
							.replace(
									"<img src=\"ikony/li_nieb_title.png\" style=\"margin:5px 5px 0px 0px;\" />",
									"");
					titlesList.add(tmpString);
					Log.i("TITLE", tmpString);
				}

			}

			if (links_nodes.length > 0) {
				for (Object linksNode : links_nodes) {
					String s = linksNode.toString();
					linksList.add(s);
					Log.i("LINKS", s);
				}
			}

			int itemCount = titlesList.size();
			names = new String[itemCount];
			links = new String[itemCount];
			Log.i("LINKSAll", Integer.toString(itemCount));
			for (int i = 0; i < itemCount; i++) {
				names[i] = titlesList.get(i);
				links[i] = linksList.get(i);
				Log.i("LINKSXXX", Integer.toString(i + 1));
			}

		}
	}
}